package io.gitee.skyarthur1987.leporidae.delayqueue.core;

import io.gitee.skyarthur1987.leporidae.delayqueue.api.DelayQueuePollEventHandler;
import io.gitee.skyarthur1987.leporidae.delayqueue.dto.BatchDelayQueueTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.util.Assert;

import java.util.Map;
import java.util.Optional;

/**
 * 延时队列轮询事件监听器
 * Created by skyarthur on 2023/1/28
 */
@Slf4j
public class DelayQueuePollEventListener {
    private final Map<String, DelayQueuePollEventHandler> topic2Handler;

    public DelayQueuePollEventListener(Map<String, DelayQueuePollEventHandler> topic2Handler) {
        this.topic2Handler = topic2Handler;
    }

    @EventListener
    public void onEvent(DelayQueuePollEvent event) {
        Assert.notNull(event, "DelayQueuePollEvent cannot be null!");
        log.info("DelayQueuePollEvent onEvent, event: {}", event.toPrint());
        String topic = Optional.ofNullable(event.getTask()).map(BatchDelayQueueTask::getTopic).orElse(null);
        DelayQueuePollEventHandler handler = Optional.ofNullable(topic).map(x -> topic2Handler.getOrDefault(x, null))
                .orElseThrow(() ->
                        new IllegalThreadStateException(String.format("find no handler for topic: %s", topic)));
        handler.handle(event);
    }
}
